<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="queryMyOrderList">
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button type="primary" :icon="CirclePlus" @click="openInsertDialog">创建新订单</el-button>
      </template>
      <template #orderNumber="scope">
        <el-button type="primary" link @click="toCustomersDetail(scope.row)"> {{ scope.row.orderNumber }}</el-button>
      </template>
      <template #createDate="scope">
        {{ scope.row.createDate.replace("T", " ").split(".")[0] }}
      </template>
      <template #updateDate="scope">
        {{ scope.row.updateDate.replace("T", " ").split(".")[0] }}
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="EditPen" @click="openUpdateDialog(scope.row)">编辑</el-button>
        <el-dropdown style="margin-top: 2px; margin-left: 5px">
          <el-button type="primary" link>更多...</el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="openOrderDetailViewDialog(scope.row)">查看明细</el-dropdown-item>
              <el-dropdown-item @click="openFillOrderDetail(scope.row)">填报明细</el-dropdown-item>
              <el-dropdown-item>作废</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
    </ProTable>
    <!-- 新增对话框 -->
    <el-dialog width="30%" title="创建新订单" v-model="insertDialogVisible">
      <el-form ref="insertFormRef" :model="insertParam" :rules="ruleForm" label-width="150px" class="demo-ruleForm">
        <el-form-item label="订单编码" prop="orderNumber">
          <el-input v-model="insertParam.orderNumber"></el-input>
        </el-form-item>
        <el-form-item label="订单名称" prop="orderName">
          <el-input v-model="insertParam.orderName"></el-input>
        </el-form-item>
        <el-form-item label="客户" prop="customersId">
          <el-select v-model="insertParam.customersId" @change="insertChangeFilter">
            <el-option
              v-for="item in customers"
              :key="item.customersId"
              :value="item.customersId"
              :label="item.customersName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单金额" prop="totalAmount">
          <el-input-number v-model="insertParam.totalAmount"></el-input-number>
        </el-form-item>
        <el-form-item label="订单备注">
          <el-input v-model="insertParam.orderRemark" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="insertDialogVisible = false">取消</el-button>
          <el-popconfirm title="是否创建新订单" placement="top-start" @confirm="addOrder(insertFormRef)">
            <template #reference>
              <el-button type="primary">提交</el-button>
            </template>
          </el-popconfirm>
        </span>
      </template>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog width="30%" title="修改订单信息" v-model="updateDialogVisible">
      <el-form ref="updateFormRef" :model="updateParam" :rules="ruleForm" label-width="150px" class="demo-ruleForm">
        <el-form-item label="订单编码" prop="orderNumber">
          <el-input v-model="updateParam.orderNumber"></el-input>
        </el-form-item>
        <el-form-item label="订单名称" prop="orderName">
          <el-input v-model="updateParam.orderName"></el-input>
        </el-form-item>
        <el-form-item label="客户" prop="customersId">
          <el-select v-model="updateParam.customersId" @change="updateChangeFilter">
            <el-option
              v-for="item in customers"
              :key="item.customersId"
              :value="item.customersId"
              :label="item.customersName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单金额" prop="totalAmount">
          <el-input-number v-model="updateParam.totalAmount"></el-input-number>
        </el-form-item>
        <el-form-item label="订单备注">
          <el-input v-model="updateParam.orderRemark" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="updateDialogVisible = false">取消</el-button>
          <el-popconfirm title="是否修改订单信息" placement="top-start" @confirm="updateOrder(updateFormRef)">
            <template #reference>
              <el-button type="primary">修改</el-button>
            </template>
          </el-popconfirm>
        </span>
      </template>
    </el-dialog>

    <!-- 填报订单明细 -->
    <el-dialog width="60%" title="填报订单明细" v-model="detailDialogVisible">
      <div style="display: flex; gap: 10px">
        <el-card class="box-card" style="flex: 0 0 35%; height: 500px">
          <el-form ref="detailFormRef" :model="detailParam" :rules="detailRuleForm" labelWidth="110" class="demo-ruleForm">
            <el-form-item label="订单明细编号" prop="orderDetailNumber">
              <el-input v-model="detailParam.orderDetailNumber"></el-input>
            </el-form-item>
            <el-form-item label="商品" prop="commodityId">
              <el-select v-model="detailParam.commodityId" @change="detailCommodityChangeFilter">
                <el-option
                  v-for="item in commodityList"
                  :key="item.commodityId"
                  :label="item.commodityName + '  $' + item.price"
                  :value="item.commodityId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="商品数量" prop="commodityCount">
              <el-input-number v-model="detailParam.commodityCount"></el-input-number>
            </el-form-item>
            <el-form-item label="总金额" prop="totalAmount">
              <el-input-number v-model="detailParam.totalAmount"></el-input-number>
            </el-form-item>
            <el-form-item label="是否外采">
              <el-radio-group v-model="detailParam.isOffshoreProcurement">
                <el-radio :label="0" :value="0">否</el-radio>
                <el-radio :label="1" :value="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="外采单据" v-if="detailParam.isOffshoreProcurement === 1" prop="offshoreProcurementReceipts">
              <UploadImg v-model:image-url="detailParam.offshoreProcurementReceipts">
                <template #empty>
                  <el-icon><Picture /></el-icon>
                  <span>请上传图片</span>
                </template>
              </UploadImg>
            </el-form-item>
            <el-form-item>
              <el-button type="danger">重置</el-button>
              <el-button type="primary" @click="addOrderDetail(detailFormRef)">添加</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <el-card style="flex: 1" class="box-card" title="卡片标题">
          <el-table :data="addOrderDetailParam.orderDetailList">
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column property="commodityName" label="商品名称" width="150"></el-table-column>
            <el-table-column property="commodityCount" label="商品数量"></el-table-column>
            <el-table-column property="totalAmount" label="总金额"></el-table-column>
            <el-table-column property="isOffshoreProcurement" label="是否外采"></el-table-column>
            <el-table-column fixed="right" label="操作" width="120">
              <template #default="scope">
                <el-button link size="small" type="primary" @click="deleteDetailRow(scope.row)"> 删除 </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="insertOrderDetail()">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看订单明细对话框 -->
    <el-dialog width="50%" title="订单明细" v-model="detailViewDialogVisible" style="height: 550px">
      <div class="table-box" style="height: 450px">
        <ProTable
          :toolButton="[]"
          ref="orderDetailViewProTable"
          :initParam="detailViewInitParam"
          :columns="detailTableColumns"
          :request-api="queryOrderDetailList"
        >
          <template #createDate="scope">
            {{ scope.row.createDate.replace("T", " ").split(".")[0] }}
          </template>
          <template #updateDate="scope">
            {{ scope.row.updateDate.replace("T", " ").split(".")[0] }}
          </template>
          <template #isOffshoreProcurement="scope">
            <el-tag>{{ scope.row.isOffshoreProcurement === 1 ? "是" : "否" }}</el-tag>
          </template>
          <template #offshoreProcurementReceipts="scope">
            <el-link
              v-if="scope.row.offshoreProcurementReceipts"
              :href="scope.row.offshoreProcurementReceipts"
              target="_blank"
              :underline="false"
              type="primary"
              rel="noopener noreferrer"
            >
              <el-icon style="margin-right: 3px"><View /></el-icon>
              查看外采单据
            </el-link>
          </template>
          <!-- 表格操作 -->
          <template #operation="scope">
            <el-button type="primary" link :icon="Delete">删除</el-button>
          </template>
        </ProTable>
      </div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts" name="myOrder">
import { ref, reactive, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import {
  CirclePlus,
  Delete,
  EditPen,
  Download,
  Upload,
  View,
  Refresh,
  ElementPlus,
  More,
  Picture
} from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import ProTable from "@/components/ProTable/index.vue";
import UploadImg from "@/components/Upload/Img.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { orderStatusEnum, statusEnum, statusFieldNames } from "@/enums/httpEnum";
import {
  CreateOrderDetailParam,
  CreateOrderParam,
  EditOrderInfoParam,
  HxOrderDetail,
  OrderDetailParam,
  QueryOrderDetailListParam,
  QueryOrderResult
} from "@/api/interface/order";
import {
  createOrder,
  createOrderDetail,
  editOrderInfo,
  editOrderStatus,
  queryMyOrderList,
  queryOrderDetailList
} from "@/api/modules/order";
import { HxCustomers } from "@/api/interface/customers";
import { queryCustomers } from "@/api/modules/customers";
import { HxCommodity } from "@/api/interface/commodity";
import { queryCommodityList } from "@/api/modules/commodity";

import { useRoute } from "vue-router";

const router = useRouter();

const proTable = ref<ProTableInstance>();

/** 新增对话框是否可见 */
const insertDialogVisible = ref(false);

/** 修改对话框是否可见 */
const updateDialogVisible = ref(false);

const detailDialogVisible = ref(false);

/** 新增表单Form */
const insertFormRef = ref<FormInstance>();

/** 修改表单Form */
const updateFormRef = ref<FormInstance>();

/** 新增初始化参数 */
const initInsertParam = {
  orderName: "",
  orderNumber: "",
  totalAmount: 0
};

/** 新增参数 */
const insertParam = reactive<CreateOrderParam>({
  orderName: "",
  orderNumber: "",
  totalAmount: 0
});

/** 修改参数 */
const updateParam = reactive<EditOrderInfoParam>({
  orderId: "",
  orderName: "",
  orderNumber: "",
  orderRemark: "",
  customersId: "",
  customersName: "",
  totalAmount: 0
});

/** 客户列表 */
let customers = ref<HxCustomers[]>([]);

/** form表单验证规则 */
const ruleForm = reactive<FormRules>({
  orderName: [{ required: true, message: "请输入订单名称", trigger: "change" }],
  orderNumber: [{ required: true, message: "请输入订单编号", trigger: "change" }],
  customersId: [{ required: true, message: "请选择客户", trigger: "change" }],
  totalAmount: [{ required: true, message: "请输入订单金额", trigger: "change" }]
});

/** 表格配置项 */
const columns = reactive<ColumnProps<QueryOrderResult>[]>([
  { type: "selection", fixed: "left", width: 70 },
  { type: "index", label: "", width: 80 },
  {
    prop: "orderNumber",
    label: "订单编号",
    width: 150,
    search: { el: "input", tooltip: "请输入订单编号" }
  },
  {
    prop: "orderName",
    label: "订单名称",
    width: 120,
    search: { el: "input", tooltip: "请输入订单名称" }
  },

  {
    prop: "orderStatus",
    label: "订单状态",
    tag: true,
    enum: orderStatusEnum,
    search: { el: "select", props: { filterable: true } },
    fieldNames: statusFieldNames
  },
  {
    prop: "totalAmount",
    label: "订单金额"
  },
  {
    prop: "customersName",
    label: "客户名称"
  },
  {
    prop: "createDate",
    label: "创建时间",
    width: 200
  },
  {
    prop: "createUserName",
    label: "创建人",
    width: 120
  },
  { prop: "operation", label: "操作", fixed: "right", width: 330 }
]);

/** 创建订单选择客户时填入客户信息 */
const insertChangeFilter = (val: string) => {
  if (val) {
    insertParam.customersName = customers.value.find(p => p.customersId == val)?.customersName;
  }
};

/** 修改订单时选择客户填入客户信息 */
const updateChangeFilter = (val: string) => {
  if (val) {
    updateParam.customersName = customers.value.find(p => p.customersId == val)?.customersName;
  }
};

/** 初始化客户信息 */
const initCustomers = async () => {
  const { data } = await queryCustomers({});
  customers.value = [...data];
};

/** 打开新增对话框 */
const openInsertDialog = async () => {
  insertDialogVisible.value = true;
  await initCustomers();
};

/** 打开修改对话框 */
const openUpdateDialog = async (param: QueryOrderResult) => {
  updateDialogVisible.value = true;
  Object.assign(updateParam, param);
  await initCustomers();
};

/** 新增订单 */
const addOrder = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      await createOrder(insertParam);
      ElMessage.success("创建新订单成功");
      insertDialogVisible.value = false;
      Object.assign(insertParam, initInsertParam);
      proTable.value?.getTableList();
    } else {
      ElMessage.error("请填入必填数据");
    }
  });
};

/** 修改订单 */
const updateOrder = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      await editOrderInfo(updateParam);
      ElMessage.success("修改订单成功");
      updateDialogVisible.value = false;
      Object.assign(insertParam, initInsertParam);
      proTable.value?.getTableList();
    } else {
      ElMessage.error("请填入必填数据");
    }
  });
};

/** 商品列表 */
const commodityList = ref<HxCommodity[]>([]);

/** 单条明细初始化参数 */
const initDetailParam = {
  commodityId: "",
  commodityName: "",
  commodityCount: 0,
  totalAmount: 0,
  isOffshoreProcurement: 0,
  offshoreProcurementReceipts: ""
};

/** 单条明细初始化参数 */
const detailParam = reactive<OrderDetailParam>({
  orderDetailNumber: "",
  commodityId: "",
  commodityName: "",
  commodityCount: 0,
  totalAmount: 0,
  isOffshoreProcurement: 0,
  offshoreProcurementReceipts: ""
});

/** 批量新增明细参数 */
const addOrderDetailParam = reactive<CreateOrderDetailParam>({
  orderId: "",
  orderDetailList: []
});

/** 填报订单明细Form表单 */
const detailFormRef = ref<FormInstance>();

/** 填报订单明细Form表单验证规则 */
const detailRuleForm = reactive<FormRules>({
  orderDetailNumber: [{ required: true, message: "请输入订单明细编号", trigger: "blur" }],
  commodityId: [{ required: true, message: "请选择商品", trigger: "blur" }],
  totalAmount: [
    { required: true, message: "请输入总金额", trigger: "blur" },
    {
      validator: (_, value, callback) => {
        if (value === 0 || value === "0") {
          callback(new Error("总金额必须大于 0"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  commodityCount: [
    { required: true, message: "请输入商品数量", trigger: "blur" },
    {
      validator: (_, value, callback) => {
        if (value === 0 || value === "0") {
          callback(new Error("商品数量必须大于 0"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  offshoreProcurementReceipts: [
    {
      validator: (_, value, callback) => {
        if (detailParam.isOffshoreProcurement === 1 && !value) {
          callback(new Error("外采单据不能为空"));
        } else {
          callback();
        }
      },
      trigger: "change"
    }
  ]
});

/** 填报订单明细选择商品事件 */
const detailCommodityChangeFilter = (val: string) => {
  detailParam.commodityName = commodityList.value.find(p => p.commodityId === val)?.commodityName;
};

/** 添加订单明细到参数 */
const addOrderDetail = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      addOrderDetailParam.orderDetailList.push({ ...detailParam });
      Object.assign(detailParam, initDetailParam);
    } else {
      ElMessage.error("请填入必填数据");
    }
  });
};

/** 从参数中去除订单明细 */
const deleteDetailRow = (param: OrderDetailParam) => {
  const index = addOrderDetailParam.orderDetailList.indexOf(param);
  if (index !== -1) {
    addOrderDetailParam.orderDetailList.splice(index, 1);
  }
};

/** 提交订单明细到后台 */
const insertOrderDetail = async () => {
  if (addOrderDetailParam.orderDetailList) {
    await createOrderDetail(addOrderDetailParam);
    ElMessage.success("填报订单明细成功");
    detailDialogVisible.value = false;
  }
};

/** 打开明细填报对话框 */
const openFillOrderDetail = async (param: QueryOrderResult) => {
  detailDialogVisible.value = true;
  addOrderDetailParam.orderId = param.orderId;
  const { data } = await queryCommodityList({});
  commodityList.value = [...data];
};

/** 修改订单状态 */
const updateOrderStatus = async (param: QueryOrderResult, status: number) => {
  await editOrderStatus({ orderId: param.orderId, orderStatus: status });
  ElMessage.success("修改订单状态成功");
};

const detailViewDialogVisible = ref(false);

const orderDetailViewProTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const detailViewInitParam = reactive<QueryOrderDetailListParam>({ orderId: "" });

const detailTableColumns = reactive<ColumnProps<HxOrderDetail>[]>([
  { type: "index", label: "", width: 80 },
  {
    prop: "commodityName",
    label: "商品名称",
    width: 150
  },
  {
    prop: "commodityCount",
    label: "商品编码",
    width: 120
  },

  {
    prop: "totalAmount",
    label: "总金额"
  },
  {
    prop: "isOffshoreProcurement",
    label: "是否外采",
    width: 100
  },
  {
    prop: "offshoreProcurementReceipts",
    label: "外采单据",
    width: 150
  },
  {
    prop: "createDate",
    label: "创建时间",
    width: 200
  },
  {
    prop: "createUserName",
    label: "创建者",
    width: 200
  },
  {
    prop: "previewDate",
    label: "审核时间",
    width: 200
  },
  {
    prop: "previewUserName",
    label: "审核者",
    width: 200
  },
  { prop: "operation", label: "操作", fixed: "right", width: 100 }
]);

const openOrderDetailViewDialog = (param: QueryOrderResult) => {
  detailViewDialogVisible.value = true;
  detailViewInitParam.orderId = param.orderId;

  nextTick(() => {
    if (orderDetailViewProTable.value) {
      orderDetailViewProTable.value.searchInitParam.orderId = param.orderId;
      orderDetailViewProTable.value.getTableList();
    }
  });
};

const toCustomersDetail = (param: QueryOrderResult) => {
  router.push(`/order/myOrder/customersDetail?params=detail-page`);
};
</script>
